package com.earl.spider.common.onlinecourse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.earl.spider.config.ChromeConfig;
import com.earl.spider.constants.SpiderConfig;
import com.earl.spider.entity.po.Course;
import com.earl.spider.entity.po.UserInfo;
import com.earl.spider.util.DateUtil;
import com.earl.spider.util.PropUtil;
import com.earl.spider.util.SpiderUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.internal.StringUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
public class OnlineCourseOperation {

    private WebDriver driver;

    private UserInfo userInfo;

    public OnlineCourseOperation() throws Exception {
        String readConfig = PropUtil.readConfig(SpiderConfig.USER_INFO.getConfigKey());
        this.userInfo = JSON.parseObject(readConfig, UserInfo.class);
        this.driver = ChromeConfig.init(false);
        OnlineCourseInit.login(driver, userInfo);
    }

    public void start() throws Exception {
        String studyUrl = userInfo.getBaseUrl() + "yTeachOutlineController.do?yStudentStudy";
        SpiderUtil.requestData(studyUrl, driver);
        List<WebElement> webElements = SpiderUtil.getUntil(() -> driver.findElements(By.xpath(".//div[@class='datagrid-view2']/div[2]/table/tbody/tr")), 60, List.class);
        if (CollectionUtils.isEmpty(webElements)) {
            return;
        }
        for (WebElement webElement : webElements) {
            String courseName = webElement.findElement(By.xpath("./td[@field='courseName']")).getText().trim();
            WebElement element = webElement.findElement(By.xpath("./td[@field='opt']/div/a[1]"));

            SpiderUtil.elementJsClick(element, driver);
            //专业教育
            switch (courseName) {
                //专业教育
                case "专业教育":
                    studyProfessional(courseName);
                    break;
                //计算机应用基础（二）
                case "计算机应用基础（二）":
                    //studyComputer(courseName);
                    break;
                //英语（二）（上）
                case "英语（二）（上）":
                    studyEnglish(courseName);
                    break;
                //网络教育导论
                case "网络教育导论":
                    studyProfessional(courseName);
                    break;
                case "微机原理与应用":
                    studyEnglish(courseName);
                    break;
                case "概率论与数理统计":
                    studyProfessional(courseName);
                    break;
                case "毛泽东思想和中国特色社会主义理论体系概论":
                    studyProfessional(courseName);
                    break;
                case "英语（二）（下）":
                    studyProfessional(courseName);
                    break;
                case "网络教育统考辅导":
                    studyProfessional(courseName);
                    break;
                case "离散数学":
                    studyProfessional(courseName);
                    break;
            }
        }

    }

    /**
     * 专业教育
     */
    private void studyProfessional(String courseName) throws InterruptedException {
        String studyXpath = ".//div[@class='easyui-panel panel-body panel-body-noheader panel-body-noborder panel-noscroll']/div/div[2]/div[2]//div[2]/div[2]/table/tbody/tr";
        List<WebElement> studyWebelements = SpiderUtil.getUntil(() -> driver.findElements(By.xpath(studyXpath)), 60, List.class);
        if (CollectionUtils.isEmpty(studyWebelements)) {
            return;
        }
        for (WebElement studyWebelement : studyWebelements) {
            WebElement element = studyWebelement.findElement(By.xpath("./td[@field='opt']/div/a"));
            String classContent = studyWebelement.findElement(By.xpath("./td[@field='knowledgePointContent']")).getText();
            //判断该课程有没有读
            String readConfig = PropUtil.readConfig(SpiderConfig.CLASS_READ_INFO.getConfigKey());
            List<Course> courses = JSONArray.parseArray(readConfig, Course.class);
            boolean flg = Boolean.FALSE;
            if (!CollectionUtils.isEmpty(courses)) {
                for (Course cours : courses) {
                    if (cours.getClassTable().equals(courseName) && cours.getClassContent().equals(classContent)) {
                        log.info("{}->{}已读,跳到下一节", courseName, classContent);
                        flg = Boolean.TRUE;
                        break;
                    }
                }
            }
            if (flg) {
                continue;
            }
            log.info("正在播放{}视频", classContent);
            if (StringUtils.isEmpty(element)) {
                return;
            }
            String onclick = element.getAttribute("onclick");
            ((JavascriptExecutor) driver).executeScript(onclick);
            SpiderUtil.getUntil(() -> {
                WebElement webElement = SpiderUtil.getElement(By.className("ui_loading"), driver);
                if (webElement != null) {
                    String style = webElement.getAttribute("style");
                    if (!StringUtil.isBlank(style) && style.contains("display: none")) {
                        return true;
                    }
                }
                return null;
            }, 60);
            Thread.sleep(2000);
            WebElement frameElement = SpiderUtil.getElement(By.xpath(".//div[@class='ui_content ui_state_full']/iframe"), driver);
            if (frameElement != null) {
                driver.switchTo().frame(frameElement);
                /*String clickJs = "document.getElementsByClassName('vjs-big-play-button')[0].click()";
                ((JavascriptExecutor) driver).executeScript(clickJs);*/
                WebElement clickElement = SpiderUtil.getElement(By.className("vjs-big-play-button"), driver);
                /*SpiderUtil.elementJsClick(clickElement,driver);*/
                clickElement.click();
                Thread.sleep(10 * 1000);
                /*WebElement finishWebElement = SpiderUtil.getUntil(() -> driver.findElement(By.xpath(".//div[@class='video-js vjs-big-play-centered vjs-default-skin vjs-paused learningVideo-dimensions vjs-controls-enabled vjs-workinghover vjs-v7 vjs-user-active']")), 120, WebElement.class);
                if (StringUtils.isEmpty(finishWebElement)) {
                    log.info("网络加载缓慢，请重试...");
                    return;
                }*/
                log.info("开始播放");
                String totalTime2 = SpiderUtil.getUntil(() -> {
                    String totalTime = driver.findElement(By.className("vjs-duration-display")).getAttribute("innerHTML").replace(":", "");
                    if (StringUtils.isEmpty(totalTime) || totalTime.matches("0+")) {
                        return null;
                    }
                    return totalTime;
                }, 30, String.class);
                while (true) {
                    String startTime = driver.findElement(By.className("vjs-current-time-display")).getAttribute("innerHTML").replace(":", "");
                    if (totalTime2.compareTo(startTime) == 0) {
                        log.info("播放结束");
                        Thread.sleep(5000);
                        writeConfig(courseName, classContent);
                        break;
                    }
                    Thread.sleep(10000);
                    log.info("正在播放{}", classContent);
                }
                driver.switchTo().defaultContent();
                WebElement uiClose = SpiderUtil.getElement(By.className("ui_close"), driver);
                if (!StringUtils.isEmpty(uiClose)) {
                    SpiderUtil.elementJsClick(uiClose, driver);
                }
            }

        }

    }

    /**
     * 英语
     */
    private void studyEnglish(String courseName) throws InterruptedException {
        String studyXpath = ".//div[@class='easyui-panel panel-body panel-body-noheader panel-body-noborder panel-noscroll']/div/div[2]/div[2]//div[2]/div[2]/table/tbody/tr";
        List<WebElement> studyWebelements = SpiderUtil.getUntil(() -> driver.findElements(By.xpath(studyXpath)), 60, List.class);
        if (CollectionUtils.isEmpty(studyWebelements)) {
            return;
        }
        for (WebElement studyWebelement : studyWebelements) {
            WebElement element = studyWebelement.findElement(By.xpath("./td[@field='opt']/div/a"));
            String classContent = studyWebelement.findElement(By.xpath("./td[@field='knowledgePointContent']")).getText();
            //判断该课程有没有读
            String readConfig = PropUtil.readConfig(SpiderConfig.CLASS_READ_INFO.getConfigKey());
            List<Course> courses = JSONArray.parseArray(readConfig, Course.class);
            boolean flg = Boolean.FALSE;
            if (!CollectionUtils.isEmpty(courses)) {
                for (Course cours : courses) {
                    if (cours.getClassTable().equals(courseName) && cours.getClassContent().equals(classContent)) {
                        log.info("{}->{}已读,跳到下一节", courseName, classContent);
                        flg = Boolean.TRUE;
                        break;
                    }
                }
            }
            if (flg) {
                continue;
            }
            log.info("正在播放{}视频", classContent);
            if (StringUtils.isEmpty(element)) {
                return;
            }
            String onclick = element.getAttribute("onclick");
            ((JavascriptExecutor) driver).executeScript(onclick);
            SpiderUtil.getUntil(() -> {
                WebElement webElement = SpiderUtil.getElement(By.className("ui_loading"), driver);
                if (webElement != null) {
                    String style = webElement.getAttribute("style");
                    if (!StringUtil.isBlank(style) && style.contains("display: none")) {
                        return true;
                    }
                }
                return null;
            }, 60);
            Thread.sleep(2000);
            WebElement frameElement = SpiderUtil.getElement(By.xpath(".//div[@class='ui_content ui_state_full']/iframe"), driver);
            if (frameElement != null) {
                driver.switchTo().frame(frameElement);
                WebElement clickElement = SpiderUtil.getElement(By.className("mejs-overlay-button"), driver);
                clickElement.click();
                Thread.sleep(10 * 1000);
                String totalTime1 = driver.findElement(By.className("mejs-duration")).getAttribute("innerHTML").replace(":", "");
                while (totalTime1.matches("0+")){
                    WebElement clickElement1 = SpiderUtil.getElement(By.className("mejs-overlay-button"), driver);
                    clickElement1.click();
                }
                log.info("开始播放");
                String totalTime2 = SpiderUtil.getUntil(() -> {
                    String totalTime = driver.findElement(By.className("mejs-duration")).getAttribute("innerHTML").replace(":", "");
                    if (StringUtils.isEmpty(totalTime) || totalTime.matches("0+")) {
                        return null;
                    }
                    return totalTime;
                }, 30, String.class);
                Integer totalTime2Int = Integer.valueOf(totalTime2);
                while (true) {
                    String startTime = driver.findElement(By.className("mejs-currenttime")).getAttribute("innerHTML").replace(":", "");
                    if (startTime.matches("0+")) {
                        log.info("播放结束");
                        writeConfig(courseName, classContent);
                        break;
                    }
                    Thread.sleep(10000);
                    log.info("正在播放{}", classContent);
                }
                driver.switchTo().defaultContent();
                WebElement uiClose = SpiderUtil.getElement(By.className("ui_close"), driver);
                if (!StringUtils.isEmpty(uiClose)) {
                    SpiderUtil.elementJsClick(uiClose, driver);
                }
            }

        }

    }

    /**
     * 计算机应用基础（二）
     */
    private void studyComputer(String courseName) throws Exception {
        WebElement until = SpiderUtil.getUntil(() -> driver.findElement(By.xpath(".//div[@class='datagrid-cell datagrid-cell-c3-opt']/a")), 60, WebElement.class);
        if (StringUtils.isEmpty(until)) {
            return;
        }
        String onclick = until.getAttribute("onclick");
        ((JavascriptExecutor) driver).executeScript(onclick);
        SpiderUtil.getUntil(() -> {
            WebElement webElement = SpiderUtil.getElement(By.className("ui_loading"), driver);
            if (webElement != null) {
                String style = webElement.getAttribute("style");
                if (!StringUtil.isBlank(style) && style.contains("display: none")) {
                    return true;
                }
            }
            return null;
        }, 60);
        List<WebElement> aWebElement = getClassContentList();

        if (CollectionUtils.isEmpty(aWebElement)) {
            return;
        }
        String thisHandle = driver.getWindowHandle();
        for (int i = 0; i < aWebElement.size(); i++) {
            WebElement webElement = aWebElement.get(i);
            String classContent = webElement.getText().trim();
            //判断该课程有没有读
            String readConfig = PropUtil.readConfig(SpiderConfig.CLASS_READ_INFO.getConfigKey());
            List<Course> courses = JSONArray.parseArray(readConfig, Course.class);
            boolean flg = Boolean.FALSE;
            if (!CollectionUtils.isEmpty(courses)) {
                for (Course cours : courses) {
                    if (cours.getClassTable().equals(courseName) && cours.getClassContent().equals(classContent)) {
                        log.info("{}->{}已读,跳到下一节", courseName, classContent);
                        flg = Boolean.TRUE;
                        break;
                    }
                }
            }
            if (flg) {
                continue;
            }
            SpiderUtil.elementJsClick(webElement, driver);
            Set<String> windowHandles = driver.getWindowHandles();
            for (String handle : windowHandles) {
                if (!handle.equals(thisHandle)) {
                    driver.switchTo().window(handle);
                    if (driver.getTitle().contains("Video")) {
                        break;
                    }
                }
            }
            Thread.sleep(2 * 1000);
            SpiderUtil.getElement(By.className("mejs-overlay-button"), driver).click();
            Thread.sleep(10 * 1000);
            log.info("播放");
            String totalTime2 = SpiderUtil.getUntil(() -> {
                String totalTime = driver.findElement(By.className("mejs-duration")).getAttribute("innerHTML").replace(":", "");
                if (StringUtils.isEmpty(totalTime) || totalTime.matches("0+")) {
                    return null;
                }
                return totalTime;
            }, 30, String.class);
            Thread.sleep(2000);
            while (true) {
                String startTime = driver.findElement(By.className("mejs-currenttime")).getAttribute("innerHTML").replace(":", "");
                int count = Integer.valueOf(totalTime2) - Integer.valueOf(startTime);
                if (count > 10) {
                    log.info("正在播放");
                    Thread.sleep(10000);
                } else {
                    log.info("播放结束");
                    Thread.sleep(count * 1000);
                    writeConfig(courseName, classContent);
                    break;
                }
            }
            driver.close();
            driver.switchTo().window(thisHandle);
            aWebElement = getClassContentList();
        }
        driver.switchTo().defaultContent();
    }

    private List<WebElement> getClassContentList() {
        WebElement frameElement = SpiderUtil.getElement(By.xpath(".//div[@class='ui_content ui_state_full']/iframe"), driver);
        driver.switchTo().frame(frameElement);
        List<WebElement> aWebElement = SpiderUtil.getElements(By.xpath(".//body/table/.//a"), driver);
        return aWebElement;
    }

    private static void writeConfig(String courseName, String content) {
        String readConfig = PropUtil.readConfig(SpiderConfig.CLASS_READ_INFO.getConfigKey());
        List<Course> courses = JSONArray.parseArray(readConfig, Course.class);
        if (CollectionUtils.isEmpty(courses)) {
            courses = new ArrayList<>();
        }
        Course course = new Course();
        course.setClassTable(courseName);
        course.setClassContent(content);
        course.setStatus("1");
        course.setLastTime(DateUtil.getNetTime());
        courses.add(course);
        String json = JSONObject.toJSONString(courses);
        PropUtil.writeConfig(SpiderConfig.CLASS_READ_INFO.getConfigKey(), json);
    }

    /**
     * 关闭浏览器
     */
    public void closeBrowser() {
        try {
            driver.quit();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
